/**
 * localStorage中保存商品的方法
 */

const KEY = 'goods'
// const KEY2 = 'goodsCount'

export const getGoods = () => {
  // 从localStorage中获取内容
  const goodsObj = JSON.parse(localStorage.getItem(KEY) || '{}')

  return goodsObj
}

/**
  * 传入进来的参数 {goodsId:87,count:3}
  */
export const saveGoods = (goods) => {
  // goodsObj中存储的数据如下  {87:3,88:2}
  const goodsObj = getGoods()

  if (goodsObj[goods.goodsId]) {
    goodsObj[goods.goodsId] = goodsObj[goods.goodsId] + goods.count
  } else {
    goodsObj[goods.goodsId] = goods.count
  }

  // 存储起来
  localStorage.setItem(KEY, JSON.stringify(goodsObj))

  // 获取总数量并且返回
  return getTotalCount()
}

// 更改商品的数量
export const updateGoods = (goods) => {
  // goodsObj中存储的数据如下  {87:3,88:2}
  const goodsObj = getGoods()

  goodsObj[goods.goodsId] = goods.count

  // 存储起来
  localStorage.setItem(KEY, JSON.stringify(goodsObj))

  // 获取总数量并且返回
  return getTotalCount()
}

// 根据id删除对应的商品
export const deleteGoodsById = (goodsId) => {
  // goodsObj中存储的数据如下  {87:3,88:2}
  const goodsObj = getGoods()

  delete goodsObj[goodsId]

  // 存储起来
  localStorage.setItem(KEY, JSON.stringify(goodsObj))

  // 获取总数量并且返回
  return getTotalCount()
}

/**
  * 获取总数量
  */
export const getTotalCount = () => {
  const localGoods = getGoods()
  let totalCount = 0
  for (const key in localGoods) {
    totalCount += localGoods[key]
  }

  localStorage.setItem('goodsCount', totalCount)

  return totalCount
}
